# coding=UTF-8
'''
Created on 2018年12月11日

@author: lijie
'''
import logging
import os
from time import sleep
import time

from selenium import webdriver
import yaml

from utilites.verification import Verification


class DriverAction:
    
    base_path = os.path.dirname(os.path.dirname(__file__))+'/driver'
    def start_browser(self,browserType="0"):
        if browserType == "0":
            driver_exe = "/chromedriver2.37.exe"
            driver_path = self.base_path+driver_exe  # 妞瑰崬濮╅弬鍥︽閸忋劏鐭惧锟�
            self.dr = webdriver.Chrome(executable_path=driver_path)
        elif browserType == "1":
            driver_exe = "geckodriver.exe"
            driver_path = os.path.abspath(self.base_path + driver_exe)  # 妞瑰崬濮╅弬鍥︽閸忋劏鐭惧锟�
            self.dr = webdriver.Firefox(executable_path=driver_path)
        elif browserType == "2":
            driver_exe = "IEDriverServer.exe"
            driver_path = os.path.abspath(self.base_path + driver_exe)  # 妞瑰崬濮╅弬鍥︽閸忋劏鐭惧锟�
            self.dr = webdriver.Ie(executable_path=driver_path)
        else:
            driver_exe = "/chromedriver2.37.exe"
            driver_path = os.path.abspath(self.base_path + driver_exe)  # 妞瑰崬濮╅弬鍥︽閸忋劏鐭惧锟�
            self.dr = webdriver.Chrome(executable_path=driver_path)
        self.dr.get("bout:blank")
        self.dr.maximize_window()
        self.dr.implicitly_wait(30)
        return self.dr

class Common:   
    
    logger=None        
    driver=None          #类变量driver，全局其他地方通过这个类变量来访问driver对象， don't move and change,very important!!!
    def set_driver(self,dr):
        Common.driver=dr
        return Common.driver
    
    current_path=os.path.dirname(__file__)
    
    def wait_sleep(self,i):
        n=1
        while n<=i:
            sleep(n)
            print('INFO - Execute wait '+str(n)+' second')
            n+=1
    
    def timestamp(self):
        t=time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
        return t
    
    def logger_info(self,messages):
        print("INFO - "+messages)
        Common.logger.info(messages)
        
        
    def logger_error(self,messages):
        Verification().set_fail(messages)
        Common.logger.error(messages)
    
    def get_app_config(self):
        with open(Common.current_path+"/../enviro_config/app.yml",'r',encoding='utf-8') as f:
            app_info = yaml.load(f.read())
        return app_info
    
    def get_current_run_config(self):
        with open(Common.current_path+"/../case/run_info.yml",'r',encoding='utf-8') as f:
            run_config = yaml.load(f.read())
        return run_config
    
    def get_interface_info(self):
        with open(Common.current_path+"/../enviro_config/interface_info.yml",'r',encoding='utf-8') as f:
            inter_info = yaml.load(f.read())
        return inter_info
    
    def get_database_config(self):
        with open(Common.current_path+"/../enviro_config/database.yml",'r',encoding='utf-8') as f:
            db_config = yaml.load(f.read())
        return db_config

    def set_element_display(self,dr,elt,index=0):  
        '''将页面元素由隐藏变成可见
        args： str elt，需要可见的元素
              number index，元素的下标，默认第一个元素
        author: lijie
        create date: 2018-04-23
        example： set_element_display("select",1)
        '''  
        js = "document.querySelectorAll('"+elt+"')["+str(index)+"].style.display='block';"
        dr.execute_script(js) 
        
    def wait_element(self,dr,xpath):
        isDisplay=False
        n=0
        while isDisplay==False and n<=30:
            isDisplay=dr.find_element_by_xpath(xpath).is_displayed()
            n+=1
            sleep(1)
            print('wait element '+xpath+' for '+str(n)+' second')
        if n>=30:
            self.logger_error('web element display timeout!pls check the page!!')  
       
    def starting(self):
        run_info=self.get_current_run_config()
        print("--------------------------------------------------------------------------------")
        print("start testing on: "+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        print("run at environment: "+run_info['_envir'])
        print("--------------------------------------------------------------------------------")
        dr=self.login()
        return dr
    
    def end(self):
        Common.driver.quit()
        print("--------------------------------------------------------------------------------")
        print("testing end at: "+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        print("--------------------------------------------------------------------------------")
    
    def get_current_handle(self,dr):
        return dr.current_window_handle
    
    def restore_handle(self,dr,handle):
        dr.switch_to_window(handle)
        
    def pop_up_displayed(self,dr,title):
        hts=[]
        for whs in dr.window_handles:
            dr.switch_to_window(whs)
            hts.append([whs,dr.title])
            
        if len(hts)>0:
            for ht in hts:
                if ht[1]==title:
                    dr.switch_to_window(ht[0])
                    return True                 
        else:
            return False
        
    def wait_popup_page(self,dr,title, timeout=30):
        Common().logger_info("Waiting popup window for title-->"+title)
        done=False
        start = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
   
        while not done and (int(time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())))-int(start)<timeout):
            self.sleep(1)
            done = True
            done = done and self.pop_up_displayed(dr,title)
#       
        if(int(time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())))-int(start)-int(start)>timeout):
            Common().logger_error("Waiting popup page takes more then #{timeout} seconds.")
                
    def switch_to_frame_by_xpath(self,dr,xpath):
        print("<-- switch to frame by xpath --> "+xpath)
        dr.switch_to_frame(dr.find_element_by_xpath(xpath))
    
    def get_logger(self,log_dir):
        fh = logging.FileHandler(log_dir,encoding='utf-8')             #创建一个文件流并设置编码utf8
        logger = logging.getLogger()                         #获得一个logger对象，默认是root
        logger.setLevel(logging.INFO)                        #设置最低等级debug
        fm = logging.Formatter("%(asctime)s --- %(message)s")  #设置日志格式
        logger.addHandler(fh)                                  #把文件流添加进来，流向写入到文件
        fh.setFormatter(fm)                                    #把文件流添加写入格式
        return logger      
    
    